import { Component } from "react";
import Taro from "@tarojs/taro";
import { ActionSheet, SafeArea, ConfigProvider } from "@taroify/core"
import { View, Text, Image } from "@tarojs/components";
import { observer } from "mobx-react";
import i18n from "i18n-js";
import { GButton } from "@/components/GButton";
import Alert from "@/components/Alert";
import { UserState_Store_Key } from "@/models/userState";
import { DynamicColors, GStyleSheet } from "@/utils/DarkMode";
import ListItem from "@/components/ListItem";
import Avatar from '@/components/Avatar';
import { norInject, INorInjectProps } from "@/models";
import PageContainer from "@/components/PageContainer";
import InputAlert from "@/components/Alert/inputAlert";
import Toast from "@/utils/Toast";
import { uploadImage } from '@/services/account';
import logout from "@/utils/logout";
import BindPhoneTip from "../mine/BindPhoneTip";

interface IProps extends INorInjectProps {

}

const dstyle = GStyleSheet.create({
  userInfo: {
    justifyContent: 'flex-start',
  },
  avatar: {
    width: 50,
    height: 50,
  },
  value: {
    color: DynamicColors.titleTextColor,
    wordBreak: 'break-all',
  },
  deleteText: {
    color: DynamicColors.deleteButton
  }
});

@norInject(UserState_Store_Key)
@observer
class Mine extends Component<IProps> {

  state = {
    nameAlertShow: false,
    pickImageShow: false,
    logoutShow: false,
  }

  componentDidMount() {
    this.queryData();
  }

  queryData = () => {
    const { userState } = this.props;
    if (userState) {
      userState.getUserInfo();
    }
  }

  showNickNameAlert = () => {
    this.setState({ nameAlertShow: true });
  }

  hideNickNameAlert = () => {
    this.setState({ nameAlertShow: false });
  }

  showPickImage = () => {
    this.setState({ pickImageShow: true });
  }

  hidePickImage = () => {
    this.setState({ pickImageShow: false });
  }

  uploadFile = async (url: string) => {
    Toast.loading(i18n.t('AVATAR_UPLOADING'));
    const res = await uploadImage({ uri: url, name: 'file' });
    console.log(res);
    if (res.success) {
      this.changeUserInfo({ avatar: res.data.sourceUrl });
    } else {
      Toast.hideLoading();
      Toast.error(i18n.t('AVATAR_UPLOAD_FAIL'));
    }
  }

  rename = async (name: string) => {
    if (name && name.length > 0) {
      this.hideNickNameAlert();
      Toast.loading('');
      await this.changeUserInfo({ nickname: name });
    } else {
      Toast.info(i18n.t('PLEASE_INPUT_NICKNAME'));
    }
  }

  changeUserInfo = async ({ avatar, nickname }: { avatar?: string, nickname?: string }) => {
    const { userState, languageKey } = this.props;
    const param: any = { lang: languageKey }
    if (avatar) {
      param.avatar = avatar;
    }
    if (nickname) {
      param.nickname = nickname;
    }
    await userState?.changeUserInfo(param)
    Toast.hideLoading();
  }

  chooseImageFromCamera = () => {
    this.hidePickImage();
    Taro.chooseMedia({
      sourceType: ['camera'],
      count: 1,
      success: ({ tempFiles }) => {
        if (tempFiles && tempFiles.length > 0) {
          this.uploadFile(tempFiles[0].tempFilePath);
        }
      },
      fail: res => {
        console.log('chooseImageFromCamera', res);
      },
    });
  }

  chooseImageFromAlbum = () => {
    this.hidePickImage();
    Taro.chooseMedia({
      sourceType: ['album'],
      count: 1,
      mediaType: ['image'],
      success: ({ tempFiles }) => {
        if (tempFiles && tempFiles.length > 0) {
          this.uploadFile(tempFiles[0].tempFilePath);
        }
      },
    });
  }

  showLogoutAlert = () => {
    // wx.openPrivacyContract()
    this.setState({ logoutShow: true })
  };

  hideLogoutAlert = () => {
    this.setState({ logoutShow: false })
  };

  logoutClick = () => {
    this.hideLogoutAlert();
    logout(false);
    Taro.navigateBack();
  };

  goToBindPhone = () => {
    Taro.navigateTo({ url: '/pages/account/bindPhone/index' });
  }

  goToDestructionAccount = () => {
    Taro.navigateTo({ url: '/pages/account/destructionAccount/index' });
  }

  render() {

    const styles = dstyle.style;
    const { userState } = this.props;
    const { nameAlertShow, pickImageShow, logoutShow } = this.state;
    console.log('userState', userState);

    const phone = userState?.userInfo.mobile;
    return (
      <PageContainer title={i18n.t('PERSONAL_DATA')} >
        <View style={{ display: 'flex', height: '100%', flexDirection: 'column' }}>
          <View style={{ flex: 1, }}>
            <ListItem
              style={{ marginTop: 15 }}
              extra={<Avatar style={styles.avatar} src={userState?.userInfo.avatar} />}
              arrow
              onPress={this.showPickImage}
            >
              {i18n.t('AVATAR')}
            </ListItem>
            <ListItem
              arrow
              extra={<Text style={styles.value}>{userState?.userInfo.nickname}</Text>}
              onPress={this.showNickNameAlert}
            >
              {i18n.t('NICKNAME')}
            </ListItem>
            <ListItem
              arrow={!!phone}
              onPress={this.goToBindPhone}
              extra={!!phone ? <Text style={styles.value}>{phone}</Text> : <BindPhoneTip />}
            >
              {i18n.t('PHONE_NUMBER')}
            </ListItem>
            <ListItem arrow style={{ marginTop: 20 }} onPress={this.goToDestructionAccount}>
              <Text style={styles.deleteText}>{i18n.t('CANCELLATION_OF_ACCONUT')}</Text>
            </ListItem>
          </View>
          <View style={{ marginBottom: 30, height: 80 }}>
            <GButton
              style={{ borderColor: '#333' }}
              textStyle={{ color: '#333' }}
              primary
              text={i18n.t("LOG_OUT")}
              onPress={this.showLogoutAlert}
            />
          </View>
        </View>
        <ActionSheet
          open={pickImageShow}
          onCancel={this.hidePickImage}
          onClose={this.hidePickImage}
          onSelect={(e) => { console.log(e) }}
        >
          <ConfigProvider theme={{ actionSheetSubnameFontSize: '16px' }}>
            <ActionSheet.Action onClick={this.chooseImageFromCamera}>
              {i18n.t('TAKE_A_PICTURE')}
            </ActionSheet.Action>
            <ActionSheet.Action onClick={this.chooseImageFromAlbum}>
              {i18n.t('CHOOSE_FROM_PHOTOS')}
            </ActionSheet.Action>
          </ConfigProvider>
          <ActionSheet.Button type='cancel'>{i18n.t('CANCEL')}</ActionSheet.Button>
          <SafeArea position='bottom' />
        </ActionSheet>
        <InputAlert
          defaultValue={userState?.userInfo.nickname}
          visible={nameAlertShow}
          title={i18n.t('NICKNAME')}
          onCancel={this.hideNickNameAlert}
          onConfirm={this.rename}
          okText={
            <Text style={{ color: DynamicColors.tintColor.value }}>{i18n.t('CONFIRM')}</Text>
          }
        />
        <Alert
          title={i18n.t("LOGOUT_TIPS")}
          visible={logoutShow}
          onCancel={this.hideLogoutAlert}
          onConfirm={this.logoutClick}
        />
      </PageContainer>
    );
  }
}

export default Mine;
